package com.songshuai.webapi.crm.service.impl;

import com.songshuai.webapi.baseapi.dto.LoginUserDto;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.BeanToMapUtil;
import com.songshuai.webapi.baseapi.utils.SnowFlakeUtil;
import com.songshuai.webapi.common.redis.RedisUtil;
import com.songshuai.webapi.crm.feign.PermissionClient;
import com.songshuai.webapi.crm.feign.SchoolMasterNumberClient;
import com.songshuai.webapi.crm.feign.SchoolMasterSourceClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * Created by yubo on 12/18/2018.
 */
public class BaseServiceImpl {

    @Autowired
    protected RedisUtil redisUtil;

    @Resource
    PermissionClient permissionClient;

    @Autowired
    protected SnowFlakeUtil snowFlakeUtil;

    @Resource
    SchoolMasterNumberClient schoolMasterNumberClient;

    @Resource
    SchoolMasterSourceClient schoolMasterSourceClient;


    /*
   获取当前登录用户的用户名
    */
    protected String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        String name = String.valueOf(principal);
        return name;
    }

    /**
     * 获取当前登录用户（使用时记得判空）
     * @return
     */
    protected LoginUserDto getCurrentUser() {
        String username = this.getUserName();
        QueryResponse currentUser = permissionClient.getCurrentUser(getBearerToken(), username);
        if (null == currentUser) {
            return null;
        } else {
            if (0 == currentUser.getCode()) {
                Object data = currentUser.getData();
                LoginUserDto userDto = BeanToMapUtil.toBean((LinkedHashMap) data, LoginUserDto.class);
                return userDto;
            } else {
                return null;
            }

        }
    }

    /**
     * 获取当前登录用户ID
     *
     * @return
     */
    protected Integer getCurrentUserId() {
        LoginUserDto currentUser = this.getCurrentUser();
        if (null == currentUser) {
            return null;
        } else {
            return currentUser.getId();
        }
    }


    protected String getOriginalToken() {
        String id = redisUtil.getString(getUserName());
        if (StringUtils.isBlank(id)) {
            return null;
        } else {
            return redisUtil.getString(id);
        }
    }

    protected String getBearerToken() {
        String token = getOriginalToken();
        if (null == token) {
            return null;
        }
        return "Bearer " + token;
    }


    /**
     * 禁用 用户后，强制用户退出登录
     */
    protected void forbiddenLoginUser(String id) {
        redisUtil.del(id);
    }
}
